/**
 * 申请报销action类
 * @author 郑翎
 * 2015-10-1 11:07:43
 */
package com.cbts.action.travel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.cbts.entity.ApplayReim;
import com.cbts.entity.BusinessTravel;
import com.cbts.entity.BusinessTravelList;
import com.cbts.entity.Receipt;
import com.cbts.service.info.VerifierService;
import com.cbts.service.travel.ApplayReimService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

public class ApplayReimAction extends ActionSupport {

	private ApplayReimService applayReimService;					//报销的业务逻辑接口
	private VerifierService verifierService;						//差旅审核业务逻辑接口
	
	private List<BusinessTravelList> businessTravelLists;			//出差记录列表
	private List<BusinessTravel> businessTravels;					//出差详情列表
	private List<Receipt> receipts;									//收据列表
	
	private String travelorder;										//出差单号
	private ApplayReim applayReim;									//报销记录
	private BusinessTravelList businessTravelList;					//出差记录
	
	private String downloadRootPath = "/files/";					//可以是前台一个页面传入,也可以是手动指定,其作用是指定下载文件的根目录
	private String userFilePath = "";								//用户文件路径
	private ArrayList<String> filelist = new ArrayList<String>();	//文件列表
	private String userid;											//获取session中的userid
	private String errormessage;									//错误信息反馈
	
	/**
	 *获得用户“报销不通过”、“待报销”和审核通过的出差列表 
	 * @return getsuccess 跳转到申请报销页面
	 * @return geterror 获取异常，跳转到异常处理首页
	 */
	public String getNoApplayTravelList() {
		try {
			
			businessTravelLists = applayReimService
					.getNoApplayTravelList(this.getUserid());
			return "getsuccess";
		} catch (Exception e) {
			e.printStackTrace();
			return "geterror";
		}
	}

	/**
	 * 根据出差单号获取具体的出差信息列表和收据
	 * @return SUCCESS 跳转到审核报销详情页面
	 * @return ERROR 跳转到异常处理页面
	 */
	
	public String getTravelInfoList() {

		try {
			
			// 根据出差单号获取出差列表
			this.businessTravelList = applayReimService
					.getTravelListByOrder(this.travelorder);
			// 根据出差单号获取出差信息列表
			this.businessTravels = applayReimService
					.getTravelInfoList(this.travelorder);
			// 根据出差单号获得报销信息
			this.applayReim = applayReimService.getApplayReim(this.travelorder);
			// 根据出差单号获得收据列表
			this.receipts = applayReimService.getReceiptFile(this.travelorder);
			// 根据收据列表筛选收据文件
			
			 dowLoadList(receipts,this.getUserid());

			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 保存报销记录
	 * @return savesuc 跳转到申请报销详情页面
	 * @return saveerr 跳转到异常处理页面
	 */
	public String saveApplayReim(){
		
		boolean b = false;
		
		try {
			
			b = applayReimService.saveApplayReimByValues(applayReim);
			if (b) {
				List<BusinessTravelList> needApplayTravelLists = verifierService.getBusinessTravelLists("待报销");
				if(needApplayTravelLists!=null){
					Map session=ServletActionContext.getContext().getSession();
					session.put("needApplay", needApplayTravelLists.size());
				}
				return "savesuc";
			}
				
			else
				return "saveerr";
		} catch (Exception e) {
			e.printStackTrace();
			return "saveerr";
		}
	}
	
	public boolean dowLoadList(List<Receipt> receipts,String userID) throws Exception {

		Map session = ServletActionContext.getContext().getSession();
		session.put("fileuserid", userID);
		userFilePath = downloadRootPath+userID+"/";
		// 指定下载目录
		String upload = ServletActionContext.getServletContext().getRealPath(
				userFilePath);
		// 清理filelist
		filelist.clear();
		// 遍历文件
		refreshFileList(upload);

		ActionContext context = ActionContext.getContext();
		Map request = (Map) context.get("request");

		if (filelist != null) {
			// 格式化文件信息,包括文件名和地址
			formatFileMap(filelist, userFilePath,receipts);
			return true;
		} else {
			request.put("errorMessage", "没有相关的下载文件");
			return false;
		}
	}

	/**
	 * 将指定文件路径下的文件全部遍历出来
	 */
	public void refreshFileList(String strPath) {
		
		File dir = new File(strPath);
		
		if (dir.exists() == false) {
			dir.mkdirs();
		}
		
		File[] files = dir.listFiles();

		if (files == null)
			return;
		
		for (int i = 0; i < files.length; i++) {
			
			if (files[i].isDirectory()) {
				refreshFileList(files[i].getAbsolutePath());
			} else {
				String filePath = files[i].getPath();
				filelist.add(filePath);
			}
		}
	}

	/**
	 * 格式化输出数据存入Map,形式文件名+文件服务端路径
	 * @param filelist  遍历出来的文件路径
	 * @param downloadRootPath 指明服务器下载的文件,便于从遍历出来的文件中取得服务端路径
	 */
	private void formatFileMap(ArrayList<String> filelist,
			String downloadRootPath,List<Receipt> receipts) {

		List<Map<String, String>> listMaps = new ArrayList<Map<String, String>>();
		List<Receipt> temReceipts = new ArrayList<Receipt>();
		Map<String, String> hotelFileMap = new HashMap<String, String>();	// 存放住宿的收据及路径
		Map<String, String> traficeFileMap = new HashMap<String, String>();	// 存放交通的收据及路径
		Map<String, String> mealFileMap = new HashMap<String, String>();	// 存放餐饮的收据及路径
		Map<String, String> elseFileMap = new HashMap<String, String>();	// 存放其他的收据及路径
		
		ActionContext context = ActionContext.getContext();
		Map request = (Map) context.get("request");

		for (int i = 0; i < receipts.size(); i++) {
			temReceipts.add(receipts.get(i));
		}
		
		receipts.clear();
		
		// 得到服务下载的根路径,并将/换成\\,这样便于替换
		String formatDownloadRootPath = downloadRootPath
				.replaceAll("/", "\\\\");

		for (String filePath : filelist) {

			// 得到下载的相对路径
			String downloadPath = filePath.substring(filePath
					.indexOf(formatDownloadRootPath));
			// 将得到的相对路径的\\转换成/
			String formatDownloadPath = downloadPath.replaceAll("\\\\", "/");
			// 得到文件名
			String filename = formatDownloadPath.substring(formatDownloadPath
					.lastIndexOf("/") + 1);
			// 这就不用考虑设置编码了，再后面统一使用javascript的encodeURI函数
			for (int i = 0; i < temReceipts.size(); i++) {

				Receipt receipt = temReceipts.get(i);
				if (filename.equals(receipt.getId().getAfilename())) {
					
					receipts.add(receipt);
					
					if (receipt.getFileType().equals("交通")) {
						
						traficeFileMap.put(filename, receipt.getRemark());
						
					} else if (receipt.getFileType().equals("餐饮")) {
						
						mealFileMap.put(filename, receipt.getRemark());
						
					} else if (receipt.getFileType().equals("住宿")) {
						
						hotelFileMap.put(filename, receipt.getRemark());
						
					} else if (receipt.getFileType().equals("其他")) {
						
						elseFileMap.put(filename, receipt.getRemark());
						
					}
				}
			}
			
		}
		System.err.println("receipts.size():"+receipts.size());
		request.put("receiptssize", receipts.size());
		request.put("errormessage", errormessage);
		errormessage = null;
		request.put("traficeFileMap", traficeFileMap);
		request.put("mealFileMap", mealFileMap);
		request.put("hotelFileMap", hotelFileMap);
		request.put("elseFileMap", elseFileMap);
	}

	public List<BusinessTravelList> getBusinessTravelLists() {
		return businessTravelLists;
	}

	public void setBusinessTravelLists(
			List<BusinessTravelList> businessTravelLists) {
		this.businessTravelLists = businessTravelLists;
	}

	public List<BusinessTravel> getBusinessTravels() {
		return businessTravels;
	}

	public void setBusinessTravels(List<BusinessTravel> businessTravels) {
		this.businessTravels = businessTravels;
	}

	public ApplayReim getApplayReim() {
		return applayReim;
	}

	public void setApplayReim(ApplayReim applayReim) {
		this.applayReim = applayReim;
	}

	public List<Receipt> getReceipts() {
		return receipts;
	}

	public void setReceipts(List<Receipt> receipts) {
		this.receipts = receipts;
	}

	public String getTravelorder() {
		return travelorder;
	}

	public void setTravelorder(String travelorder) {

		this.travelorder = travelorder;
	}

	public BusinessTravelList getBusinessTravelList() {
		return businessTravelList;
	}

	public void setBusinessTravelList(BusinessTravelList businessTravelList) {
		this.businessTravelList = businessTravelList;
	}

	public ApplayReimService getApplayReimService() {
		return applayReimService;
	}

	public void setApplayReimService(ApplayReimService applayReimService) {
		this.applayReimService = applayReimService;
	}

	public String getDownloadRootPath() {
		return downloadRootPath;
	}

	public void setDownloadRootPath(String downloadRootPath) {
		this.downloadRootPath = downloadRootPath;
	}
	
	public String getUserid() throws Exception{
		try {
			userid = ServletActionContext.getContext().getSession().get("userid").toString();
		} catch (Exception e) {
			throw e;
		}
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getErrormessage() {
		return errormessage;
	}

	public void setErrormessage(String errormessage) {
		this.errormessage = errormessage;
	}

	public VerifierService getVerifierService() {
		return verifierService;
	}

	public void setVerifierService(VerifierService verifierService) {
		this.verifierService = verifierService;
	}
	
}
